from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from app.core.deps import get_current_active_user
from app.db.database import get_db
from app.models.product import Product, ProductImage, ProductTag, ProductDetail
from app.models.category import Category
from app.models.tag import Tag
from app.schemas.product import (
    ProductCreate, ProductUpdate, Product as ProductSchema,
    ProductImageCreate, ProductDetailCreate, ProductDetailUpdate,
    ProductListResponse
)

router = APIRouter()

@router.get("/", response_model=ProductListResponse)
def get_products(
    skip: int = 0,
    limit: int = 100,
    category_id: int = None,
    name: str = None,
    db: Session = Depends(get_db)
):
    """获取商品列表"""
    query = db.query(Product)
    if category_id:
        query = query.filter(Product.category_id == category_id)
    if name:
        query = query.filter(Product.name.contains(name))
    
    # 获取总数
    total = query.count()
    
    # 获取分页数据
    products = query.offset(skip).limit(limit).all()
    
    # 为每个商品添加图片信息
    for product in products:
        # 获取商品的第一张图片
        first_image = db.query(ProductImage).filter(
            ProductImage.product_id == product.id
        ).order_by(ProductImage.sort_order, ProductImage.id).first()
        
        if first_image:
            product.first_image_url = f"/api/v1/upload/images/{first_image.id}"
        
        # 获取所有图片
        images = db.query(ProductImage).filter(
            ProductImage.product_id == product.id
        ).order_by(ProductImage.sort_order, ProductImage.id).all()
        product.images = images
    
    # 计算分页信息
    page = (skip // limit) + 1 if limit > 0 else 1
    total_pages = (total + limit - 1) // limit if limit > 0 else 1
    
    return ProductListResponse(
        items=products,
        total=total,
        page=page,
        page_size=limit,
        total_pages=total_pages
    )

@router.post("/", response_model=ProductSchema)
def create_product(
    product: ProductCreate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    """创建新商品"""
    # 检查分类是否存在
    category = db.query(Category).filter(Category.id == product.category_id).first()
    if not category:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Category not found"
        )
    
    db_product = Product(**product.dict())
    db.add(db_product)
    db.commit()
    db.refresh(db_product)
    return db_product

@router.get("/{product_id}", response_model=ProductSchema)
def get_product(product_id: int, db: Session = Depends(get_db)):
    """获取单个商品"""
    product = db.query(Product).filter(Product.id == product_id).first()
    if product is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product not found"
        )
    
    # 获取商品的第一张图片
    first_image = db.query(ProductImage).filter(
        ProductImage.product_id == product.id
    ).order_by(ProductImage.sort_order, ProductImage.id).first()
    
    if first_image:
        product.first_image_url = f"/api/v1/upload/images/{first_image.id}"
    
    # 获取所有图片
    images = db.query(ProductImage).filter(
        ProductImage.product_id == product.id
    ).order_by(ProductImage.sort_order, ProductImage.id).all()
    product.images = images
    
    return product

@router.put("/{product_id}", response_model=ProductSchema)
def update_product(
    product_id: int,
    product: ProductUpdate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    """更新商品"""
    db_product = db.query(Product).filter(Product.id == product_id).first()
    if db_product is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product not found"
        )
    
    update_data = product.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(db_product, field, value)
    
    db.commit()
    db.refresh(db_product)
    return db_product

@router.delete("/{product_id}")
def delete_product(
    product_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    """删除商品"""
    db_product = db.query(Product).filter(Product.id == product_id).first()
    if db_product is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product not found"
        )
    
    db.delete(db_product)
    db.commit()
    return {"message": "Product deleted successfully"}

@router.post("/{product_id}/images")
def add_product_image(
    product_id: int,
    image: ProductImageCreate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    """为商品添加图片"""
    product = db.query(Product).filter(Product.id == product_id).first()
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product not found"
        )
    
    db_image = ProductImage(**image.dict(), product_id=product_id)
    db.add(db_image)
    db.commit()
    db.refresh(db_image)
    return db_image

@router.get("/{product_id}/detail")
def get_product_detail(
    product_id: int,
    db: Session = Depends(get_db)
):
    """获取商品详情"""
    product = db.query(Product).filter(Product.id == product_id).first()
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product not found"
        )
    
    detail = db.query(ProductDetail).filter(ProductDetail.product_id == product_id).first()
    if not detail:
        # 如果没有详情，返回空的详情对象
        return {
            "rich_content": "",
            "specifications": "",
            "features": ""
        }
    
    return detail

@router.post("/{product_id}/detail")
def update_product_detail(
    product_id: int,
    detail: ProductDetailCreate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    """更新商品详情"""
    product = db.query(Product).filter(Product.id == product_id).first()
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product not found"
        )
    
    # 检查是否已有详情
    existing_detail = db.query(ProductDetail).filter(ProductDetail.product_id == product_id).first()
    if existing_detail:
        # 更新现有详情
        for field, value in detail.dict(exclude_unset=True).items():
            setattr(existing_detail, field, value)
        db.commit()
        db.refresh(existing_detail)
        return existing_detail
    else:
        # 创建新详情
        db_detail = ProductDetail(**detail.dict(), product_id=product_id)
        db.add(db_detail)
        db.commit()
        db.refresh(db_detail)
        return db_detail 